package org.jeecg.modules.mr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.mr.entity.MsMeasures;
import org.jeecg.modules.mr.entity.MsSubMeasures;
import org.jeecg.modules.mr.mapper.MsMeasuresMapper;
import org.jeecg.modules.mr.mapper.MsSubMeasuresMapper;
import org.jeecg.modules.mr.service.IMsMeasuresService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * @Description: 用水计量
 * @Author: jeecg-boot
 * @Date:   2022-02-10
 * @Version: V1.0
 */
@Service
public class MsMeasuresServiceImpl extends ServiceImpl<MsMeasuresMapper, MsMeasures> implements IMsMeasuresService {

	@Resource
	private MsMeasuresMapper msMeasuresMapper;
	@Resource
	private MsSubMeasuresMapper msSubMeasuresMapper;

	@Override
	@Transactional
	public Integer saveMain(MsMeasures msMeasures, List<MsSubMeasures> msSubMeasuresList) {
		Integer count = msMeasuresMapper.selectCount(new LambdaQueryWrapper<MsMeasures>()
				.eq(MsMeasures::getRecordId, msMeasures.getRecordId())
				.eq(MsMeasures::getDelFlag, 0).eq(MsMeasures::getIsVaild,1));
		if(count>0){
			//已存在
			return -1;
		}
		msMeasuresMapper.insert(msMeasures);
		if(msSubMeasuresList!=null && msSubMeasuresList.size()>0) {
			for(MsSubMeasures entity:msSubMeasuresList) {
				//外键设置
				entity.setMeasureId(msMeasures.getId());
				msSubMeasuresMapper.insert(entity);
			}
		}
		return 1;
	}

	@Override
	@Transactional
	public void updateMain(MsMeasures msMeasures,List<MsSubMeasures> msSubMeasuresList) {
		msMeasuresMapper.updateById(msMeasures);

		//1.先删除子表数据
		msSubMeasuresMapper.deleteByMainId(msMeasures.getId());

		//2.子表数据重新插入
		if(msSubMeasuresList!=null && msSubMeasuresList.size()>0) {
			for(MsSubMeasures entity:msSubMeasuresList) {
				//外键设置
				entity.setMeasureId(msMeasures.getId());
				msSubMeasuresMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		msSubMeasuresMapper.deleteByMainId(id);
		msMeasuresMapper.deleteById(id);
	}
	@Override
	public void delSubByMainId(String id) {
		msSubMeasuresMapper.deleteByMainId(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			msSubMeasuresMapper.deleteByMainId(id.toString());
			msMeasuresMapper.deleteById(id);
		}
	}

}
